<script setup>
import { reactive, ref } from 'vue'
import { loginAPI } from '@/api/user'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { setCookie } from '@/utils/cookie'

const ruleFormRef = ref()

const ruleForm = reactive({
  username: 'admin',
  password: 'admin123',
})

const rules = reactive({
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})

const router = useRouter()

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      // #mark
      const res = await loginAPI(ruleForm)
      setCookie(res.data.token)
      router.push('/home')
      ElMessage({
        type: 'success',
        message: '登录成功'
      })
    } else {
      console.log('error submit!')
      return false
    }
  })
}
</script>

<template>
  <div class="container"></div>
  <div class="login">
    <div class="avatar_box">
      <img src="../assets/logo.png" alt />
    </div>
    <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" class="login_form">
      <el-form-item label-width="70" label="用户名" prop="username">
        <el-input v-model.number="ruleForm.username" />
      </el-form-item>
      <el-form-item label-width="70" label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item class="btn_wrap">
        <el-button size="large" type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="scss">
.container {
  position: fixed;
  width: 100%;
  height: 100%;
  background: url('../assets/login_bg.jpg') no-repeat;
  background-size: cover;
}

.login {
  width: 450px;
  height: 300px;
  background-color: #fff;
  border-radius: 3px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);

  .avatar_box {
    width: 130px;
    height: 130px;
    border: 1px solid #eee;
    border-radius: 50%;
    padding: 10px;
    box-shadow: 0 0 10px #ddd;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;

    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #eee;
    }
  }

  .login_form {
    position: absolute;
    bottom: 0;
    width: 100%;
    padding: 0 20px;
    box-sizing: border-box;
  }

  .btn_wrap {
    :deep(.el-form-item__content) {
      justify-content: center;
    }
    :deep(.el-button) {
      width: 200px;
      background-color: rgba(3, 75, 147);
      transition: .3s;
      &:hover {
        background-color: rgba(3, 75, 147, .9);
      }
    }
  }
}
</style>